import matplotlib.pyplot as plt
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
from keras.datasets import fashion_mnist

# 加载Fashion MNIST数据集
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()

# 扩展数据维度，适应ImageDataGenerator
x_train = x_train.reshape((x_train.shape[0], 28, 28, 1))
x_test = x_test.reshape((x_test.shape[0], 28, 28, 1))

# 将像素值归一化到[0, 1]之间
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0

# 定义数据增强器
datagen = ImageDataGenerator(
    rotation_range=10,        # 随机旋转角度范围
    width_shift_range=0.1,    # 随机水平平移范围
    height_shift_range=0.1,   # 随机垂直平移范围
    shear_range=0.1,          # 随机错切变换角度
    zoom_range=0.1,           # 随机缩放范围
    horizontal_flip=False,    # 水平翻转
    fill_mode='nearest'       # 填充新创建像素的方法
)

# 拟合数据（仅当使用`featurewise_center`或`featurewise_std_normalization`时需要）
datagen.fit(x_train)
temp=datagen.flow(x_train)

# 可视化经过数据增强的图像
fig, ax = plt.subplots(1, 5, figsize=(15, 3))

for i in range(5):
    generated_img = datagen.flow(x_train, batch_size=1).next()[0].squeeze()
    ax[i].imshow(generated_img, cmap='gray')
    ax[i].axis('off')

plt.show()
# # 创建模型
# model = tf.keras.models.Sequential([
#     tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
#     tf.keras.layers.MaxPooling2D((2, 2)),
#     tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
#     tf.keras.layers.MaxPooling2D((2, 2)),
#     tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
#     tf.keras.layers.Flatten(),
#     tf.keras.layers.Dense(64, activation='relu'),
#     tf.keras.layers.Dense(10, activation='softmax')
# ])
#
# # 编译模型
# model.compile(optimizer='adam',
#               loss='sparse_categorical_crossentropy',
#               metrics=['accuracy'])
#
# # 使用数据增强器训练模型
# model.fit(datagen.flow(x_train, y_train, batch_size=32),
#           steps_per_epoch=len(x_train) / 32, epochs=10,
#           validation_data=(x_test, y_test))
#
# # 评估模型
# test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
# print(f'\n测试准确率: {test_acc}')